/*
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "plotview.h"
#include "plotstats.h"

PlotView::PlotView(QWidget *parent) : QGraphicsView(parent)
{
  scene = new PlotScene();
  setScene(scene);
  scaleView();
}

PlotView::PlotView(QList<QPointF> data, QWidget *parent) :QGraphicsView(parent)
{
  scene = new PlotScene(data);
  setScene(scene);
  scaleView();
}


/**
  resets the view and updates the data
*/
void PlotView::setData(QList<QPointF> data)
{
  delete scene;
  scene = new PlotScene(data);
  setScene(scene);
  scaleView();
}

/**
  updates the plot without resetting the view
*/
void PlotView::update(QList<QPointF> data)
{
  delete scene;
  scene = new PlotScene(data);
  setScene(scene);
}

void PlotView::scaleView()
{
  resetMatrix();
  QTransform t = transform();
  
  // flip vertically
  t.scale(1.0, -1.0);

  // scale to fit size
  QRectF rect = scene->sceneRect();
  double vScale = (size().height() / rect.height());
  double hScale = (size().width()  / rect.width());

  // add a margin
  vScale -= 0.20;
  hScale -= 0.02;

  t.scale(hScale, vScale);  
  setTransform(t);
}

void PlotView::resizeEvent(QResizeEvent* /*event*/)
{
  scaleView();
}

QSize PlotView::sizeHint() const
{
  if (scene)
  {
    QRectF rect = scene->sceneRect();
    return QSize(rect.width(), rect.height());
  }
  else
    return QSize(1000, 300);
}

PlotView::~PlotView()
{
  delete scene;
}